package com.example.shgt.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.shgt.MessageDetailActivity;
import com.example.shgt.R;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

// 消息模型类
class Message {
    private String username; // 用户名
    private int unReadNum; // 未读消息数量
    private String fromUserId; // 发送者用户 ID

    public Message(String username, int unReadNum, String fromUserId) {
        this.username = username;
        this.unReadNum = unReadNum;
        this.fromUserId = fromUserId;
    }

    public String getUsername() {
        return username;
    }

    public int getUnReadNum() {
        return unReadNum;
    }

    public String getFromUserId() {
        return fromUserId;
    }
}

// 消息适配器
class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {
    private List<Message> messages;
    private OnItemClickListener listener;

    public MessageAdapter(List<Message> messages) {
        this.messages = messages;
    }

    @NonNull
    @Override
    public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message, parent, false);
        return new MessageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
        Message message = messages.get(position);
        holder.textViewUsername.setText(message.getUsername());
        holder.textViewUnreadCount.setText("未读消息：" + message.getUnReadNum());
        holder.textViewUnreadCount.setTextColor(holder.itemView.getContext().getResources().getColor(android.R.color.holo_red_dark));

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(message);
            }
        });
    }

    @Override
    public int getItemCount() {
        return messages.size();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(Message message);
    }

    public static class MessageViewHolder extends RecyclerView.ViewHolder {
        TextView textViewUsername;
        TextView textViewUnreadCount;

        public MessageViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewUsername = itemView.findViewById(R.id.tv_username);
            textViewUnreadCount = itemView.findViewById(R.id.tv_unread_count);
        }
    }
}

public class OrderFragment extends Fragment {

    private RecyclerView recyclerViewMessages;
    private MessageAdapter messageAdapter;
    private List<Message> messageList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        LinearLayout layout = new LinearLayout(getContext());
        layout.setOrientation(LinearLayout.VERTICAL);

        // 创建并配置 Toolbar
        androidx.appcompat.widget.Toolbar toolbar = new androidx.appcompat.widget.Toolbar(getContext());
        toolbar.setBackgroundColor(getResources().getColor(R.color.my_light_primary));
        toolbar.setTitle("消息");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        layout.addView(toolbar, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        ));

        // 创建 RecyclerView
        recyclerViewMessages = new RecyclerView(getContext());
        recyclerViewMessages.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        ));
        recyclerViewMessages.setPadding(8, 8, 8, 8);
        layout.addView(recyclerViewMessages);

        // 初始化消息列表和适配器
        messageList = new ArrayList<>();
        messageAdapter = new MessageAdapter(messageList);
        recyclerViewMessages.setAdapter(messageAdapter);
        recyclerViewMessages.setLayoutManager(new LinearLayoutManager(getContext()));

        // 设置点击事件监听器
        messageAdapter.setOnItemClickListener(message -> {
            Intent intent = new Intent(getContext(), MessageDetailActivity.class);
            intent.putExtra("fromUserId", message.getFromUserId()); // 使用 fromUserId 作为参数

            // 获取当前登录用户的 ID
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("UserPrefs", getContext().MODE_PRIVATE);
            String currentUserId = sharedPreferences.getString("userId", null);
            if (currentUserId != null) {
                intent.putExtra("userId", currentUserId); // 将 userId 传递给 MessageDetailActivity
            }

            startActivity(intent);
        });

        // 获取当前登录用户的 ID
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("UserPrefs", getContext().MODE_PRIVATE);
        String currentUserId = sharedPreferences.getString("userId", null);

        // 获取消息
        if (currentUserId != null) {
            fetchMessages(currentUserId);
        }

        return layout;
    }

    private void fetchMessages(String userId) {
        String url = "https://api-store.openguet.cn/api/member/tran/chat/user?userId=" + userId;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Content-Type", "application/json")
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OrderFragment", "请求失败", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    Log.d("OrderFragment", "Response data: " + responseData);
                    parseMessages(responseData);
                } else {
                    Log.e("OrderFragment", "响应错误: " + response.code());
                }
            }
        });
    }

    private void parseMessages(String responseData) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(responseData, JsonObject.class);
        JsonArray dataArray = jsonObject.getAsJsonArray("data");

        messageList.clear();
        for (JsonElement element : dataArray) {
            JsonObject messageObject = element.getAsJsonObject();
            String username = messageObject.has("username") ? messageObject.get("username").getAsString() : "未知用户";
            int unReadNum = messageObject.has("unReadNum") ? messageObject.get("unReadNum").getAsInt() : 0;
            String fromUserId = messageObject.has("fromUserId") ? messageObject.get("fromUserId").getAsString() : ""; // 获取 fromUserId

            messageList.add(new Message(username, unReadNum, fromUserId)); // 将 fromUserId 传递给 Message 对象
        }

        requireActivity().runOnUiThread(() -> messageAdapter.notifyDataSetChanged());
    }
}
